package com.zzzzzz.content.tag;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.common.GlobalConstants;
import com.zzzzzz.core.dao.BaseDao;

@Repository
public class TagDao extends BaseDao{
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private final static String ADD = 							"insert into tag(name, refer_count, status) values(?, ?, ?)";
	private final static String EDIT_REFERCOUNT_BY_ID = 		"update tag set refer_count = refer_count+? where id = ?";
	private final static String EDIT_STATUS_BY_ID = 			"update tag set status = ? where id = ?";
	
	private final static String FIND_ID_BY_NAME = 				"select id from tag where name = ? and status = 0";
	private final static String FIND_BY_NAME = 					"select id, name, refer_count, status from tag where name = ? and status = 0";
	
	protected class TagRowMapper implements RowMapper<Tag> {
		public Tag mapRow(ResultSet rs, int rn) throws SQLException {
			Tag tag = new Tag();
			tag.setId(rs.getInt("id"));
			tag.setName(rs.getString("name"));
			tag.setReferCount(rs.getInt("refer_count"));
			tag.setStatus(rs.getInt("status"));
			return tag;
		}
	}
	
	public void add(Tag tag){
		tag.setReferCount(1);
		tag.setStatus(GlobalConstants.STATUS.NORMAL);
		
		jdbcTemplate.update(ADD, tag.getName(), tag.getReferCount(), tag.getStatus());
		int id = jdbcTemplate.queryForInt("SELECT @@IDENTITY");
		tag.setId(id);
	}
	
	public void delById(Integer id){
		this.editStatusById(id, 1);
	}
	
	public void editReferCountById(Integer tagId, Integer referCountChange){
		jdbcTemplate.update(EDIT_REFERCOUNT_BY_ID, referCountChange, tagId);
	}
	
	public void editStatusById(Integer id, Integer status){
		jdbcTemplate.update(EDIT_STATUS_BY_ID, status, id);
	}
	
	public Integer findIdByName(String name) {
		return jdbcTemplate.queryForInt(FIND_ID_BY_NAME, name);
	}
	
	public Tag findByName(String name) {
		return jdbcTemplate.queryForObject(FIND_BY_NAME, new TagRowMapper(), name);
	}
	
}

